package com.plata.base.base;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.ProxyInstrumentation;
import androidx.multidex.MultiDexApplication;

import com.plata.base.utils.CrashHandler;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class AbsBaseApp extends MultiDexApplication {

    protected List<Activity> list = new ArrayList<>();
    boolean background = false;
    int count = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        CrashHandler.getInstance().init(this);
        replaceInstrumentation();
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            @RequiresApi(29)
            public void onActivityPreCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                CommonUtil.setHandler(activity);
            }

            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                list.add(0, activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                ++count;
                if (background) {
                    background = false;
                    comeBack();
                }
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                --count;
                if (count == 0) {
                    background = true;
                }
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                list.remove(activity);
            }
        });
    }

    protected void comeBack() {

    }

    private void replaceInstrumentation() {
        if (Build.VERSION.SDK_INT >= 29) {
            return;
        }
        try {
            //先获取到当前的ActivityThread对象
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
            currentActivityThreadMethod.setAccessible(true);
            Object currentActivityThread = currentActivityThreadMethod.invoke(null);
            // 拿到原始的 mInstrumentation字段
            Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
            mInstrumentationField.setAccessible(true);
            Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
            // 创建代理对象
            Instrumentation evilInstrumentation = new ProxyInstrumentation(mInstrumentation);
            //赋值，替换为代理类
            mInstrumentationField.set(currentActivityThread, evilInstrumentation);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
        try {
            return super.registerReceiver(receiver, filter);
        } catch (Throwable e) {
            e.printStackTrace();
            return new Intent();
        }
    }

    @Override
    public void unregisterReceiver(BroadcastReceiver receiver) {
        try {
            super.unregisterReceiver(receiver);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public void unbindService(ServiceConnection conn) {
        try {
            super.unbindService(conn);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startActivity(Intent intent) {
        try {
            super.startActivity(intent);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
